//
//  PayViewController.m
//  danpin
//
//  Created by chuangjia on 3/12/2015.
//  Copyright © 2015 chuangjia. All rights reserved.
//

#import "PayViewController.h"
#import "AppDelegate.h"
#import "AlipayRequestConfig.h"
#define BOTTOM_HEIGHT 45
@interface PayViewController()<UITableViewDataSource,UITableViewDelegate,OrderDelegate>
{
    
}
@property(strong,nonatomic) UITableView *tbView;
@property(nonatomic,strong) UILabel *xuzhifuLabel;
@property(nonatomic,strong) UILabel *yingzhifuLabel;
@property(nonatomic,strong) NSString *balance;
@property(nonatomic,assign) BOOL isUseBalance;
@property(nonatomic,assign) int payType;
@property(nonatomic,strong)NSMutableArray *sectionArray;
@end

@implementation PayViewController
@synthesize delegate = _delegate;
@synthesize balance=_balance;
@synthesize payDictionary=_payDictionary;
@synthesize isUseBalance=_isUseBalance;
@synthesize payType=_payType;
@synthesize istariff_fee=_istariff_fee;
@synthesize sectionArray=_sectionArray;
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.navTitle =@"收银台";
    _balance =@"0";
    _isUseBalance = NO;
    _payType =1;
    if (!_sectionArray) {
        _sectionArray =[[NSMutableArray alloc] init];
    }
    if (self.istariff_fee) {
        _sectionArray =[NSMutableArray arrayWithObjects:@"balance",@"paytype", nil];
    }else{
        _sectionArray =[NSMutableArray arrayWithObjects:@"paytype", nil];
    }
    
    [self initUI];
    [self initBottomView];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    DLog(@"%s", __PRETTY_FUNCTION__);
}
-(void)dealloc
{
    self.balance=nil;
    self.payDictionary=nil;
    self.delegate =nil;
    DLog(@"%s", __PRETTY_FUNCTION__);
}

//======================================
//======================================
-(void)initUI
{
    _tbView = [[UITableView alloc] initWithFrame:CGRectMake(0, hightAuto(65), self.view.bounds.size.width, self.view.bounds.size.height-hightAuto(65)-BOTTOM_HEIGHT) style:UITableViewStyleGrouped];
    _tbView.delegate = self;
    _tbView.dataSource = self;
    _tbView.backgroundColor =[UIColor clearColor];
    _tbView.showsVerticalScrollIndicator = NO;
    _tbView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    [self.view addSubview:_tbView];
    //
}
#pragma mark - tableview
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _sectionArray.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSString *sctionTitle = [_sectionArray objectAtIndex:section];
    if ([sctionTitle isEqualToString:@"balance"]) {
        return 1;
    }else  if ([sctionTitle isEqualToString:@"paytype"]){
        return 2;
    }
    
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 10;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = (UITableViewCell*)[tableView  dequeueReusableCellWithIdentifier:@"cell"];
    if(cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.imageView.frame = CGRectMake(0, 7, 30, 30);
        cell.textLabel.font = FONT(14);
        cell.textLabel.textColor = [UIColor darkGrayColor];
        cell.detailTextLabel.font = FONT(12);
        cell.detailTextLabel.textColor = [UIColor lightGrayColor];
    }
    NSString *sctionTitle = [_sectionArray objectAtIndex:indexPath.section];
    if ([sctionTitle isEqualToString:@"balance"]) {
        cell.imageView.image =[UIImage imageNamed:@"noorder"];
        cell.textLabel.text =@"使用余额";
        cell.detailTextLabel.text = [NSString stringWithFormat:@"当前余额：%@",_balance];
        if ([_balance floatValue]<=0) {
            [cell setAccessoryType:UITableViewCellAccessoryNone];
            cell.textLabel.textColor = [UIColor lightGrayColor];
            cell.detailTextLabel.textColor = [UIColor lightGrayColor];
        }
        return cell;
        
    }else  if ([sctionTitle isEqualToString:@"paytype"]){
        if(indexPath.row==0)
        {
            cell.textLabel.text =@"支付宝";
            cell.detailTextLabel.text = @"推荐有支付宝账号用户使用";
            [cell setAccessoryType:UITableViewCellAccessoryCheckmark];
            
        }else if(indexPath.row==1)
        {
            cell.textLabel.text =@"微信支付";
            cell.detailTextLabel.text = @"推荐有微信支付账号用户使用";
        }
        return cell;
    }
    
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *sctionTitle = [_sectionArray objectAtIndex:indexPath.section];
    if ([sctionTitle isEqualToString:@"balance"]) {
        if ([_balance floatValue]<=0) {
            return;
        }else{
            
            UITableViewCell *cell=[self.tbView cellForRowAtIndexPath:indexPath];
            if (cell.accessoryType ==UITableViewCellAccessoryNone) {
                [cell setAccessoryType:UITableViewCellAccessoryCheckmark];
                [self refreshPayMoney:YES];
            }else{
                [cell setAccessoryType:UITableViewCellAccessoryNone];
                [self refreshPayMoney:NO];
            }
            
        }
        return;
    }else  if ([sctionTitle isEqualToString:@"paytype"]){
        NSArray *array = [tableView visibleCells];
        for (int i=1; i<array.count; i++) {
            UITableViewCell *cell = (UITableViewCell *)[array objectAtIndex:i];
            [cell setAccessoryType:UITableViewCellAccessoryNone];
        }
        
        UITableViewCell *cell=[self.tbView cellForRowAtIndexPath:indexPath];
        _payType = (int)indexPath.row;
        [cell setAccessoryType:UITableViewCellAccessoryCheckmark];
        return;
    }
}
//======================================
//
//======================================
-(void)refreshPayMoney:(BOOL)isUse
{
//    NSString *out_trade_no = [self.payDictionary stringForKey:@"out_trade_no"]; //订单ID（由商家自行制定）
//    NSString *subject = [self.payDictionary stringForKey:@"subject"]; //订单ID（由商家自行制定）
//    NSString *body = [self.payDictionary stringForKey:@"body"]; //订单ID（由商家自行制定）
    _isUseBalance = isUse;
    NSString *total_fee = [self.payDictionary stringForKey:@"total_fee"]; //订单ID（由商家自行制定）
    if (isUse) {
        float xu_fee = [total_fee floatValue] - [_balance floatValue];
        _xuzhifuLabel.hidden =NO;
        _yingzhifuLabel.hidden = NO;
        _xuzhifuLabel.frame =CGRectMake(PHOTO_FRAME_WIDTH,PHOTO_TIME_PADDING/2, self.view.frame.size.width-100, BOTTOM_HEIGHT/2);
        _xuzhifuLabel.text = [NSString stringWithFormat:@"还需支付：%.2f",xu_fee];
        _yingzhifuLabel.frame=CGRectMake(PHOTO_FRAME_WIDTH,BOTTOM_HEIGHT/2, self.view.frame.size.width-100,  BOTTOM_HEIGHT/2);
        _yingzhifuLabel.text = [NSString stringWithFormat:@"应支付：%@",total_fee];
    }else{
        _xuzhifuLabel.hidden =NO;
        _yingzhifuLabel.hidden = YES;
        _xuzhifuLabel.frame =CGRectMake(PHOTO_FRAME_WIDTH,0, self.view.frame.size.width-100, BOTTOM_HEIGHT);
        _yingzhifuLabel.frame=CGRectZero;
        _xuzhifuLabel.text = [NSString stringWithFormat:@"应支付：%@",total_fee];
    }
}
-(void)initBottomView
{
    UIView *bootmView =[[UIView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height-BOTTOM_HEIGHT, self.view.frame.size.width, BOTTOM_HEIGHT)];
    bootmView.backgroundColor =[UIColor clearColor];
    //
    UIImageView *bgImageView =[[UIImageView alloc] initWithFrame:CGRectMake(0,0, self.view.frame.size.width, BOTTOM_HEIGHT)];
    bgImageView.image =[UIImage imageNamed:@"toolbar_bg.png"];
    [bootmView addSubview:bgImageView];
    //
    _xuzhifuLabel = [[UILabel alloc] initWithFrame:CGRectMake(PHOTO_FRAME_WIDTH,PHOTO_TIME_PADDING, self.view.frame.size.width-100, BOTTOM_HEIGHT/2)];
    _xuzhifuLabel.backgroundColor=[UIColor clearColor];
    _xuzhifuLabel.textColor =[UIColor darkGrayColor];
    _xuzhifuLabel.textAlignment=NSTextAlignmentLeft;
    _xuzhifuLabel.font=FONT(13);
    _xuzhifuLabel.hidden = YES;
    [bootmView addSubview:_xuzhifuLabel];
    //
    _yingzhifuLabel = [[UILabel alloc] initWithFrame:CGRectMake(PHOTO_FRAME_WIDTH,BOTTOM_HEIGHT/2, self.view.frame.size.width-100, BOTTOM_HEIGHT/2)];
    _yingzhifuLabel.backgroundColor=[UIColor clearColor];;
    _yingzhifuLabel.textColor =[UIColor grayColor];
    _yingzhifuLabel.textAlignment=NSTextAlignmentLeft;
    _yingzhifuLabel.font=FONT(11);
    _yingzhifuLabel.hidden=YES;
    [bootmView addSubview:_yingzhifuLabel];
    //
    UIButton *buyBtn =[UIButton buttonWithType:UIButtonTypeCustom];
    buyBtn.tag=3;
    buyBtn.frame =CGRectMake(DEVICE_WIDTH-widthAuto(100), 0, widthAuto(100), BOTTOM_HEIGHT);
    buyBtn.backgroundColor= UIColorFromRGB(0xCE0202);
    buyBtn.titleLabel.font =FONT(15);
    [buyBtn setTitle:@"去付款" forState:UIControlStateNormal];
    buyBtn.contentHorizontalAlignment=UIControlContentHorizontalAlignmentCenter;
    [buyBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [buyBtn addTarget:self action:@selector(clickNavEvent:) forControlEvents:UIControlEventTouchUpInside];
    [bootmView addSubview:buyBtn];
    
    [self.view addSubview:bootmView];
    bootmView=nil;
    [self refreshPayMoney:NO];
}
-(void)clickNavEvent:(id)sender
{
    UIButton *btn =(UIButton*)sender;
    switch (btn.tag) {
        case 0:
        {
            if (self.delegate && [self.delegate respondsToSelector:@selector(payCancel)]) {
                [self.delegate payCancel];
            }
            AppDelegate *app = [[UIApplication sharedApplication]delegate];
            app.orderDelegate=nil;
            [NSObject cancelPreviousPerformRequestsWithTarget:self];
            if (self.navigationController) {
                if (self.navigationController.viewControllers.count == 1) {
                    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
                } else {
                    [self.navigationController popViewControllerAnimated:YES];
                }
            } else {
                [self dismissViewControllerAnimated:YES completion:nil];
            }
        }
            break;
        case 3:
        {
            if (self.isUseBalance && [_balance floatValue]>0)
            {
                NSString *total_fee = [self.payDictionary stringForKey:@"total_fee"]; //订单ID（由商家自行制定）
                float xu_fee = [total_fee floatValue] - [_balance floatValue];
                if (xu_fee<=0) //抵扣成功
                {
                    //更新订单列表里面支付状态
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"updateZhifuStatu" object:nil];
                    if (self.delegate && [self.delegate respondsToSelector:@selector(payOK:)]) {
                        [self.delegate payOK:self.payDictionary];
                    }
                    [NSObject cancelPreviousPerformRequestsWithTarget:self];
                    if (self.navigationController) {
                        if (self.navigationController.viewControllers.count == 1) {
                            [self.navigationController dismissViewControllerAnimated:YES completion:nil];
                        } else {
                            [self.navigationController popViewControllerAnimated:YES];
                        }
                    } else {
                        [self dismissViewControllerAnimated:YES completion:nil];
                    }
                }else
                {
                    NSMutableDictionary *pdict = [NSMutableDictionary dictionary];
                    [pdict setValue:[[NSString stringWithFormat:@"%@",[self.payDictionary objectForKey:@"out_trade_no"]] replaceNullString] forKey:@"out_trade_no"];
                    [pdict setValue:[[NSString stringWithFormat:@"%@",[self.payDictionary objectForKey:@"subject"]] replaceNullString] forKey:@"subject"];
                    [pdict setValue:[[NSString stringWithFormat:@"%@",[self.payDictionary objectForKey:@"body"]] replaceNullString] forKey:@"body"];
                    [pdict setValue:[NSString stringWithFormat:@"%f",xu_fee] forKey:@"total_fee"];
                    [self alipay:pdict];
                }
            }else
            {
                NSMutableDictionary *pdict = [NSMutableDictionary dictionary];
                [pdict setValue:[[NSString stringWithFormat:@"%@",[self.payDictionary objectForKey:@"out_trade_no"]] replaceNullString] forKey:@"out_trade_no"];
                [pdict setValue:[[NSString stringWithFormat:@"%@",[self.payDictionary objectForKey:@"subject"]] replaceNullString] forKey:@"subject"];
                [pdict setValue:[[NSString stringWithFormat:@"%@",[self.payDictionary objectForKey:@"body"]] replaceNullString] forKey:@"body"];
                [pdict setValue:[self.payDictionary stringForKey:@"total_fee"] forKey:@"total_fee"];
                [self alipay:pdict];
            }
           
            
        }
            break;
        default:
            break;
    }
}
//======================================
//获取用户余额
//======================================
-(void)getuserbalance
{
    __weak typeof (self) wSelf = self;
    [BaseModel getUserBalance:nil success:^(AFHTTPRequestOperation *operation, id result) {
        if (result&&[result isKindOfClass:[NSDictionary class]]) {
            NSDictionary *resultDist =(NSDictionary*)result;
            if (resultDist && [resultDist isKindOfClass:[NSDictionary class]]) {
               _balance =[[NSString stringWithFormat:@"%@",[resultDist objectForKey:@"balance"]] replaceNullString];
                [wSelf.tbView reloadData];
            }
        }
    } failure:^(NSError *error) {

    }];
}
//======================================
//去支付
//======================================
-(void)alipay:(NSDictionary*)dict
{
    NSString *totalfee =[[NSString stringWithFormat:@"%@",[dict stringForKey:@"total_fee"]] replaceNullString];
    if ([totalfee floatValue]==0) {
        return;
    }
    NSString *tradeNO = [dict stringForKey:@"out_trade_no"]; //订单ID（由商家自行制定）
    NSString *subject = [dict stringForKey:@"subject"]; //商品标题
    NSString *body =[dict stringForKey:@"body"];
    NSString *amount = [dict stringForKey:@"total_fee"];; //商品价格
    AppDelegate *app = [[UIApplication sharedApplication]delegate];
    app.orderDelegate=self;
    __weak typeof (self) wSelf = self;
    [AlipayRequestConfig alipayWithTradeNO:tradeNO productName:subject productDescription:body amount:amount callback:^(NSDictionary *resultDic) {
        [wSelf orderPayOK:resultDic];
    }];
}
-(void)orderPayOK:(id)info
{
    NSDictionary *resultDic =(NSDictionary *)info;
    AppDelegate *app = [[UIApplication sharedApplication]delegate];
    app.orderDelegate=nil;
    NSString *memo = [resultDic objectForKey:@"memo"];
    if (memo.length>0) {
        [[ZToastManager ShardInstance] showtoast:memo];
    }
    
    NSString *resultStatus = [resultDic objectForKey:@"resultStatus"];
    if ([resultStatus isEqualToString:@"9000"]) {
        NSMutableDictionary *dcit =[NSMutableDictionary dictionary];
        [dcit setValue:@"0" forKey:@"rmb"];
        if (self.istariff_fee) {
            [dcit setValue:[self.payDictionary stringForKey:@"total_fee"] forKey:@"tariff_fee"];
        }
        [dcit setValue:[ZShare DataTOjsonString:resultDic] forKey:@"return_data"];
        [BaseModel alipayReturnUrl:dcit success:^(AFHTTPRequestOperation *operation, id result) {
            //            NSLog(@"%@",result);
        } failure:^(NSError *error) {
            
        }];
        //更新订单列表里面支付状态
        [[NSNotificationCenter defaultCenter] postNotificationName:@"updateZhifuStatu" object:nil];
        if (self.delegate && [self.delegate respondsToSelector:@selector(payOK:)]) {
            [self.delegate payOK:self.payDictionary];
        }
        [NSObject cancelPreviousPerformRequestsWithTarget:self];
        if (self.navigationController) {
            if (self.navigationController.viewControllers.count == 1) {
                [self.navigationController dismissViewControllerAnimated:YES completion:nil];
            } else {
                [self.navigationController popViewControllerAnimated:YES];
            }
        } else {
            [self dismissViewControllerAnimated:YES completion:nil];
        }
    }else  if ([resultStatus isEqualToString:@"6001"])
    {
        if (self.delegate && [self.delegate respondsToSelector:@selector(payFail)]) {
            [self.delegate payFail];
        }
    }
}

@end
